﻿using IFRS.Web;
using IFRS_Global;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IFRS.DataAccess.DAL;
using IFRS.Models;
using System.Globalization;
using System.Threading;
using vsm.CustomControl;

public partial class WIN31_GL_DEPO_4A : PageBase
{

    #region "---------- Events -----------"

    protected void Page_Load(object sender, EventArgs e)
    {
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
        if (!(Page.IsPostBack || Page.IsCallback))
        {
            this.AddClientScript();
            this.ViewMenu();
            this.SetErrorMessage();
            if (Request.QueryString["GroupName"] != null)
            {                         
                txtGL_Group.Text = Request.QueryString["GroupName"].ToString();
            }
            if (Request.QueryString["id"] != null)
            {
                this.BindData(Convert.ToInt32(Request.QueryString["id"].ToString()));
            }

        }
        else
            ClientScript.RegisterHiddenField("isPostBack", "1");
    }
    protected void btnSAVE_Click(object sender, EventArgs e)
    {
        if (!CheckDuplicateGL(form_control)) SaveData(false);
    }
    protected void btnSAVE_NEW_Click(object sender, EventArgs e)
    {
        if (!CheckDuplicateGL(form_control)) SaveData(true);
    }
    protected void btnCANCEL_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/IFRS/WIN31_1S.aspx");
    }
    protected void btnCLEAR_Click(object sender, EventArgs e)
    {
        Response.Redirect(ResolveUrl(Request.Url.AbsolutePath + "?&GroupID=" + Request.QueryString["GroupID"].ToString() + "&GroupName=" + Request.QueryString["GroupName"].ToString()));
    }
    #endregion "---------- Events -----------"

    #region "----------  Methods -----------"

    private void AddClientScript()
    {
        btnCANCEL.Attributes["OnClick"] = "if(!confirm(\"" + Resources.ifrsResource.ConfirmCancel + "\")) return false;";
        btnGL_ACCOUNT.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/GLAccount_GL.aspx?&PopUp=GL_ACCOUNT") + "','700','550');");
        btnGL_ADJ_INT_INC_PL.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/GLAccount_GL.aspx?&PopUp=GL_ADJ_INT_INC_PL") + "','700','550');");
        btnGL_ADJ_FV_BS.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/GLAccount_GL.aspx?&PopUp=GL_ADJ_FV_BS") + "','700','550');");
        btnGL_ADJ_INT_INC_ELCLS_PL.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/GLAccount_GL.aspx?&PopUp=GL_ADJ_INT_INC_ELCLS_PL") + "','700','550');");
        btnGL_ADJ_CST_BS.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/GLAccount_GL.aspx?&PopUp=GL_ADJ_CST_BS") + "','700','550');");
        btnGL_REV_CST_PL.Attributes.Add("onClick", "return popWindow('" + ResolveUrl("~/PopupPages/GLAccount_GL.aspx?&PopUp=GL_REV_CST_PL") + "','700','550');");
        this.SetTextboxAutoComplete(form_control);
    }

    private void ViewMenu()
    {
        MenuTitleBar = Resources.ifrsMenu.WIN31_GL_DEPO_4A;
    }

    private void SetTextboxAutoComplete(PlaceHolder plcReadOnly)
    {
        foreach (Control ctrl in plcReadOnly.Controls)
        {
            if (ctrl is TextboxAutoComplete)
            {
                var hidName = "hid" + ((TextboxAutoComplete)ctrl).ID.Substring(3);
                var txtName = ((TextboxAutoComplete)ctrl).ID + "_NAME";
                HiddenField hidControl = (HiddenField)plcReadOnly.FindControl(hidName);
                TextBox txtControl = (TextBox)plcReadOnly.FindControl(txtName);
                ((TextboxAutoComplete)ctrl).AddControl(hidControl.ClientID);
                ((TextboxAutoComplete)ctrl).AddControl(ctrl.ClientID);
                ((TextboxAutoComplete)ctrl).AddControl(txtControl.ClientID);
                ((TextboxAutoComplete)ctrl).ControlSearch = ctrl.ClientID;
                ((TextboxAutoComplete)ctrl).AddQueryString("bIsActive", "1");
                ((TextboxAutoComplete)ctrl).SearchKey = "GLAccount_oGLAccountCode_oGLAccountName_GL";
            }          
        }
    }

    private void SetErrorMessage()
    {
        btnSAVE.ValidationGroup = "Master";
        btnSAVE_NEW.ValidationGroup = "Master";
        reqGLAccount.SetRequiredField(lblGL_ACCOUNT, txtGL_ACCOUNT, btnSAVE);
    }

    private void BindData(int ID)
    {
        List<GLAccountPosting> glAccountPosting = new List<GLAccountPosting>();
        DataTable dt = new SPR_GLACCOUNTPOSTING().SEARCH_BYID(ID);
        if (dt.Rows.Count > 0)
        {
            ConvertHelper.ConvertDataTableToObject(dt, glAccountPosting);
            txtGL_Group.Text = glAccountPosting[0].GLGroup_NAME;
            txtGL_ACCOUNT.Text = glAccountPosting[0].GLAccount_CODE;
            txtGL_ACCOUNT_NAME.Text = glAccountPosting[0].GLAccount_NAME;
            txtGL_ADJ_CST_BS.Text = glAccountPosting[0].GL_ADJ_CST_BS_CODE;
            txtGL_ADJ_CST_BS_NAME.Text = glAccountPosting[0].GL_ADJ_CST_BS_NAME;
            txtGL_ADJ_FV_BS.Text = glAccountPosting[0].GL_ADJ_FV_BS_CODE;
            txtGL_ADJ_FV_BS_NAME.Text = glAccountPosting[0].GL_ADJ_FV_BS_NAME;
            txtGL_ADJ_INT_INC_ELCLS_PL.Text = glAccountPosting[0].GL_ADJ_INT_INC_ELCLS_PL_CODE;
            txtGL_ADJ_INT_INC_ELCLS_PL_NAME.Text = glAccountPosting[0].GL_ADJ_INT_INC_ELCLS_PL_NAME;
            txtGL_ADJ_INT_INC_PL.Text = glAccountPosting[0].GL_ADJ_INT_INC_PL_CODE;
            txtGL_ADJ_INT_INC_PL_NAME.Text = glAccountPosting[0].GL_ADJ_INT_INC_PL_NAME;
            txtGL_REV_CST_PL.Text = glAccountPosting[0].GL_REV_CST_PL_CODE;
            txtGL_REV_CST_PL_NAME.Text = glAccountPosting[0].GL_REV_CST_PL_NAME;

            hidGL_ACCOUNT.Value = glAccountPosting[0].GLAccountID.IntToString();
            hidGL_ADJ_INT_INC_PL.Value = glAccountPosting[0].GL_ADJ_INT_INC_PL_ID.IntToString();  
            hidGL_ADJ_FV_BS.Value = glAccountPosting[0].GL_ADJ_FV_BS_ID.IntToString(); 
            hidGL_ADJ_INT_INC_ELCLS_PL.Value = glAccountPosting[0].GL_ADJ_INT_INC_ELCLS_PL_ID.IntToString();
            hidGL_ADJ_CST_BS.Value = glAccountPosting[0].GL_ADJ_CST_BS_ID.IntToString();
            hidGL_REV_CST_PL.Value = glAccountPosting[0].GL_REV_CST_PL_ID.IntToString();
        }
    }

    private void SaveData(bool SaveNew)
    {
        try
        {          
            GLAccountPosting glAccountPosting = new GLAccountPosting();
            glAccountPosting.GLAccountID = hidGL_ACCOUNT.Value.AsIntIsnull();
            glAccountPosting.GLGroupID = Request.QueryString["GroupID"].AsIntIsnull();
            glAccountPosting.GL_ADJ_INT_INC_PL_ID = hidGL_ADJ_INT_INC_PL.Value.AsIntIsnull();
            glAccountPosting.GL_ADJ_FV_BS_ID = hidGL_ADJ_FV_BS.Value.AsIntIsnull();
            glAccountPosting.GL_ADJ_INT_INC_ELCLS_PL_ID = hidGL_ADJ_INT_INC_ELCLS_PL.Value.AsIntIsnull();
            glAccountPosting.GL_ADJ_CST_BS_ID = hidGL_ADJ_CST_BS.Value.AsIntIsnull();
            glAccountPosting.GL_REV_CST_PL_ID = hidGL_REV_CST_PL.Value.AsIntIsnull();
            glAccountPosting.SetStandardField();
            int iID = new SPR_GLACCOUNTPOSTING().INSERT(glAccountPosting);

            if (iID > 0)
            {
                if (SaveNew)
                {
                    this.JS_Alert(Resources.ifrsResource.SaveData, ResolveUrl(Request.Url.AbsolutePath + "?&GroupID=" + Request.QueryString["GroupID"].ToString() + "&GroupName=" + Request.QueryString["GroupName"].ToString()));
                }
                else
                {
                    this.JS_Alert(Resources.ifrsResource.SaveData, ResolveUrl(string.Format("~/IFRS/WIN31_GL_DEPO_2E.aspx?&id={0}", iID)));
                }

            }
            else
            {
                if (iID == -1)
                {
                    Utility.AlertMessage(Page, Resources.ifrsResource.Duplicate);
                }
                else
                {
                    Utility.AlertMessage(Page, Resources.ifrsResource.CanNotSaveData);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private bool CheckDuplicateGL(PlaceHolder plc)
    {
        string Alert_TextDetail = "";
        List<HiddenGL> lst_hidden = new List<HiddenGL>();
        foreach (Control ctrl in plc.Controls)
        {
            if (ctrl is HiddenField)
            {
                if (((HiddenField)ctrl).Value != "")
                    lst_hidden.Add(new HiddenGL { HiddenID = ((HiddenField)ctrl).ID, Value = ((HiddenField)ctrl).Value });
            }
        }

        var tmp = "";
        for (int i = 0; i < lst_hidden.Count; i++)
        {
            tmp = "";
            var dup_value = lst_hidden[i].Value; // ค่า Value ที่เช็คซ้ำ
            var lst = lst_hidden.Where(x => x.Value == dup_value && x.Value != "" && x.HiddenID != lst_hidden[i].HiddenID).ToList();
            foreach (var row in lst)
            {
                Label lbl_control = (Label)plc.FindControl("lbl" + row.HiddenID.Substring(3));
                tmp += lbl_control.Text + ", ";
            }
            if (lst.Count != 0 && i < lst_hidden.Count - 1)
            {
                Alert_TextDetail += "- " + ((Label)plc.FindControl("lbl" + lst_hidden[i].HiddenID.Substring(3))).Text + ", ";
                Alert_TextDetail += tmp.Substring(0, tmp.Length - 2) + "\\n";
            }

            for (int j = 0; j < lst_hidden.Count; j++)
            {
                // Clear ค่า Value ใน List<HiddenGL> ที่ซ้ำ
                if (lst_hidden[j].Value == dup_value)
                    lst_hidden[j].Value = "";
            }
        }

        if (Alert_TextDetail == "")
        {
            return false;
        }
        else
        {
            var script_alert = Resources.ifrsResource.Alert_TextHeaderGL + Alert_TextDetail;
            Utility.AlertMessage(Page, script_alert);
            return true;
        }
    }

    public class HiddenGL
    {
        public string HiddenID { get; set; }
        public string Value { get; set; }
    }
    #endregion "---------- Methods -----------"
  
}